package lancooControl;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lancooznbk.R;
import com.example.lancooznbk.model.ImpAndDifParam;
import com.example.lancooznbk.model.ListJson;
import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/24.
 */
public class Control {
    public static Gson gson;
    public static  HttpPost httpPost;
    public static HttpGet httpGet;
    public static HttpResponse httpResponse;
    public static DefaultHttpClient httpclient;

    /*
    * @Title  sendPostParams 发送post请求访问webapi返回请求数据
    * @param  httpUrl 请求的webapi地址
    * @param  json 请求参数组成的json字符串
    * */
    public static String sendPostParams(String httpUrl, String json) {
        // 返回消息
        String msg = "err";
        // HttpPost连接对象
        httpPost = new HttpPost(httpUrl);
        try {
            httpPost.addHeader("Content-Type", "application/json");
            // 设置字符集
            httpPost.setEntity(new StringEntity(json, HTTP.UTF_8));
            // 取得默认的HttpClient
            httpclient = new DefaultHttpClient();
            // 取得HttpResponse
            httpResponse = httpclient.execute(httpPost);
            // HttpStatus.SC_OK表示连接成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                msg = EntityUtils.toString(httpResponse
                        .getEntity());
                // mTextView.setText(strResult);
//                System.out.println("============sendPostParams===0000======"+msg);
                return msg;
            } else {
                msg = EntityUtils.toString(httpResponse
                        .getEntity());
//                System.out.println("============sendPostParams===1111======"+msg);
                return msg;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("============sendPostParams===2222======"+msg);
        return msg;
    }

    /**
     * @Title 组装【基本复习】和【猜题测试】列表参数的Json字符串
     * @param StuID
     * @param SubjectID
     * @param TestLayer
      * @param TestItem  0-基本复习  1-猜题测试
     * @param PageCurrent
      * @param PageSize  999999无穷大
     * @param ListState 0-未完成   1-完成
     * **/
    public static  String jsonQursListparam( String StuID,
                                             String SubjectID,
                                             String TestLayer,
                                             int TestItem,
                                             int PageCurrent,
                                             int PageSize,
                                             int ListState){
        gson = new Gson();
        ListJson mListJson = new ListJson(StuID,SubjectID,TestLayer,TestItem,PageCurrent,PageSize,ListState);
        return gson.toJson(mListJson);
    }


    /**
     * @Title 组装【重难点辅导】列表参数Json字符串
     * @param StuID
     * @param SubjectID
     * @param TestLayer
     * @param PageSize
     * @param CurrentPage
     * @param FinishedFlag
     * **/
    public static  String jsonQuesListparamZNDFD(String StuID,
                                                   String SubjectID,
                                                   String TestLayer,
                                                   int PageSize,
                                                   int CurrentPage,
                                                   int FinishedFlag){
        gson = new Gson();
        ImpAndDifParam mImpAndDifParam = new ImpAndDifParam(StuID,SubjectID,TestLayer,PageSize,CurrentPage,FinishedFlag);
        System.out.println("==========Control===========mImpAndDifParam============="+gson.toJson(mImpAndDifParam));
        return gson.toJson(mImpAndDifParam);
    }


    /*
    *@Title//判断某个字符在整个字符串中出现的次数、频率
    *@param allString：整个字符串
    *@param thisString：需要判断的字符
    * */
    public static int getStringFrequency(String allString,String thisString) {

        int count=0;
        String str =allString;//你要测试的字符串
        str = str.toLowerCase();//将字符串全部转化成小写//考虑大小写：
        //index为字符串中第一次出现c的位置，如果字符串中没有c将返回-1
        int index = str.indexOf(thisString);
        //如果字符串中有c
        while( str.indexOf(thisString)!=-1){
            count++;
            str = str.substring(str.indexOf(thisString)+1);
        }
        return count;
    }

    //输出数组
    public static void printArray(String[] array){
        for(int i=0;i<array.length;i++){
            System.out.print(""+i+"====yyyyy=="+array[i]);
            if(i==array.length-1){
                System.out.print("\n");
            }else{
                System.out.print(",");
            }
        }
    }

    /*
    * @Title 输出一个字符串数组
    * @param AllString 需要拆解的字符窜
    * @param thisString 需要判断的字符
    * @param i_begin 分隔符所占的字符数
    * */
    public static String[] returnArray(String allString,String thisString,int i_begin){
        int count=0;
        int i_strArrayflag = getStringFrequency(allString,thisString);
        String[] strArray = new String[i_strArrayflag+1];
        String strA = allString;

        while( strA.indexOf(thisString)!=-1){
            count++;
            strArray[count-1] = strA.substring(0,strA.indexOf(thisString));
            //将字符串出现c的位置之前的全部截取掉
            strA = strA.substring(strA.indexOf(thisString)+i_begin);
        }
        strArray[count] = strA;
        printArray(strArray);
        return strArray;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     * @param code
     * @return
     */
    public static String autoGenericCode(String code, int num) {
        String result = "";
        // 保留num的位数
        // 0 代表前面补充0
        // num 代表长度为4
        // d 代表参数为正数型
        result = String.format("%0" + num + "d", Integer.parseInt(code));

        return result;
    }

    /*
* ascii转化为字符
* */
    public static String asciiToString(int asc){
        char c=(char)asc;
        return String.valueOf(c);
    }


    /*
* 实现一下ImageGetter就可以让图片显示了,用于textview加载html格式图片(网络图片)
* */
    public static Html.ImageGetter imgGetter = new Html.ImageGetter() //格式语句不一定相同，只要进行网络加载图片即可
    {
        public Drawable getDrawable(String source)
        {
            Drawable drawable = null;
            try
            {
                drawable = Drawable.createFromStream(new URL(source).openStream(), "");
//                drawable.setBounds(0, 0,  drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                drawable.setBounds(0, 0,  drawable.getIntrinsicWidth()*2, drawable.getIntrinsicHeight()*2);

            }
            catch (Exception e)
            {
                return new Drawable()
                {
                    public void setColorFilter(ColorFilter cf) {}
                    public void setAlpha(int alpha) {}
                    public int getOpacity() {return 0;}
                    public void draw(Canvas canvas) {}
                };
            }
            return drawable;
        }
    };


    /*
* //截取某个特殊字符最后出现位置之后的字符串
* str_zfc：整个字符串
* str_zf：需要判断的字符
* */
    public static String lastBackString(String allString,String thisString) {

        int count=0;
        String str =allString;//你要测试的字符串
        str = str.toLowerCase();//将字符串全部转化成小写//考虑大小写：
        //index为字符串中第一次出现c的位置，如果字符串中没有c将返回-1
        int index = str.indexOf(thisString);
        //如果字符串中有c
        while( str.indexOf(thisString)!=-1){
            count++;
            //将字符串出现c的位置之前的全部截取掉
            str = str.substring(str.indexOf(thisString)+1);
        }
        System.out.println("===str===\n====8888888====\n=====str========"+str);
        return str;

    }

    /*
* //判断某个字符在整个字符串中出现的次数
* str_zfc：整个字符串
* str_zf：需要判断的字符
* */
    public static int backSum(String allString,String thisString) {

        int count=0;
        String str =allString;//你要测试的字符串
        str = str.toLowerCase();//将字符串全部转化成小写//考虑大小写：
        //index为字符串中第一次出现c的位置，如果字符串中没有c将返回-1
        int index = str.indexOf(thisString);
        //如果字符串中有c
        while( str.indexOf(thisString)!=-1){
            count++;
            str = str.substring(str.indexOf(thisString)+1);
        }

        return count;

    }


    /*
    * 判断网络是否连接成功
    * */
    public static boolean checkNetWorkStatus(Context context)
    {
        boolean result;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        if (netinfo != null && netinfo.isConnected()) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

        /*
        * ASCII码转为字符串
        * */
        public static String asciiToString(String value)
        {
            StringBuffer sbu = new StringBuffer();
            String[] chars = value.split(",");
            for (int i = 0; i < chars.length; i++) {
                sbu.append((char) Integer.parseInt(chars[i]));
            }
            return sbu.toString();
        }

        /*
        * 字符串转为ASCII码
        * */
        public static String stringToAscii(String value)
        {
            StringBuffer sbu = new StringBuffer();
            char[] chars = value.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if(i != chars.length - 1)
                {
                    sbu.append((int)chars[i]).append(",");
                }
                else {
                    sbu.append((int)chars[i]);
                }
            }
            return sbu.toString();
        }

    /*
* 获取当前试题作答的准确率(保留两位小数)
* */
    public static double getCorrectRate(float a,float b){

        BigDecimal bg   =   new   BigDecimal(a/b);
        double   rateCorrectRate   =   bg.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();

        return rateCorrectRate;
    }


}
